<?php

namespace App\Http\Controllers\Admin;

use App\Address;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\DB;
use iscms\AlismsSdk\AlibabaAliqinFcSmsNumSendRequest;
use iscms\AlismsSdk\TopClient;
use App\Manage;
use App\Role;
use App\Users;
use App\Goods;
use Illuminate\Support\Facades\Session;
use App\Orders;
use Excel;
use Mail;

date_default_timezone_set('PRC');
class OrdersController extends Controller
{
    private $PathToFile = null;

    protected $b = [];

    //定义查询数组
    protected static $field = [
        ['id'=>1,'searchtype'=>'编号'],
        ['id'=>2,'searchtype'=>'创建时间'],
        ['id'=>3,'searchtype'=>'批次号'],
        ['id'=>4,'searchtype'=>'订单编号'],
        ['id'=>5,'searchtype'=>'商品名称'],
//        ['id'=>6,'searchtype'=>'商品价格'],
        ['id'=>7,'searchtype'=>'订单总价'],
        ['id'=>8,'searchtype'=>'客户名称'],
        ['id'=>9,'searchtype'=>'客户经理'],
        ['id'=>10,'searchtype'=>'发货方式'],
        ['id'=>11,'searchtype'=>'订单地址'],
        ['id'=>12,'searchtype'=>'兑换码'],
        ['id'=>13,'searchtype'=>'订单状态'],

    ];

    //载入未审核自助订单列表
    public function index() {
        $search = input::get('searchtype');
        $param = input::get('param');
        $obj = new Orders;
        if($search == 1 ) {
            $obj = $obj->where('id','like',"%$param%");
        }elseif ($search == 2 ) {
            $obj = $obj->where('create_time','like',"%$param%");
        }elseif ($search == 3 ) {
            $obj = $obj->where('batch','like',"%$param%");
        }elseif ($search == 4 ) {
            $obj = $obj->where('order_id','like',"%$param%");
        }elseif ($search == 5 ) {
            $gname = Goods::where('goods_name','like',"%$param%")->first();
            if(!$gname) {
                return redirect()->back()->withInput()->withErrors('为搜索到该商品!');
            }
            $obj = $obj->where('goods_id','=',$gname->goods_name);
        }elseif ($search == 7 ) {
            $obj = $obj->where('total_price','like',"%$param%");
        }elseif ($search == 8 ) {
            $uname = Users::where('name','like',"%$param%")->first();
            if(!$uname) {
                return redirect()->back()->withInput()->withErrors('为搜索到该会员!');
            }
            $obj = $obj->where('user_id','=',$uname->name);
        }elseif ($search == 9 ) {
            $mname = Manage::where('username','like',"%$param%")->first();
            if(!$mname) {
                return redirect()->back()->withInput()->withErrors('为搜索到该客户经理!');
            }
            $obj = $obj->where('manage_id','=',$mname->username);
        }elseif ($search == 10 ) {
            if($param === "自取") {
                $p = 1;
            }
            if($param === "邮寄") {
                $p = 2;
            }
            $obj = $obj->where('get_way','=',$p);
        }elseif ($search == 11 ) {
            $obj = $obj->where('address','like',"%$param%");
        }elseif ($search == 12 ) {
            $obj = $obj->where('code','like',"%$param%");
        }elseif ($search == 13 ) {
            if($param === "已兑换") {
                $p = 1;
            }
            else {
                $p = 0;
            }
            $obj = $obj->where('status','=',$p);
        }
        $sid = Session::get('id');
        $roleid = Session::get('roleid');
        if($roleid == 1) {
            $list = $obj->whereNull('batch')->where('audit',0)->orderBy('create_time','desc')->Paginate(10)->toArray();
            if($list == false && !empty($search)) {
                return  redirect()->back()->withInput()->withErrors('未查询到结果！');
            }
            $searchtype = self::$field;
            $ord = $obj->whereNull('batch')->where('audit',0)->Paginate(10);
        }
        elseif ($roleid == 2 or $roleid ==3) {
            if($roleid == 3) {
                $pid = Manage::where('id',$sid)->first();
                $id = Manage::where('son_id',$pid['son_id'])->get()->toArray();
            }
            else {
                $id = Manage::where('son_id',$sid)->get()->toArray();
//                dump($id);
            }
            $d = array();
            $t = array();
            foreach ($id as $value) {
                $d[] = $value['id'];
            }
            $user = Users::whereIn('mid',$d)->get()->toArray();
            foreach ($user as $value) {
                $t[] = $value['id'];
            }
//            dump($t);
            $list = $obj->whereIn('user_id',$t)->whereNull('batch')->where('status',0)->orderBy('create_time','desc')->Paginate(10)->toArray();
//            dump($list);
            if($list == false && !empty($search)) {
                return  redirect()->back()->withInput()->withErrors('未查询到结果！');
            }
            $searchtype = self::$field;
            $ord = $obj->whereIn('user_id',$t)->where('status',0)->whereNull('batch')->Paginate(10);
        }
        else {
//            dump(Session::get('id'));
            $t = array();
            $user = Users::where('mid',Session::get('id'))->get()->toArray();
//            dump($);
            foreach ($user as $value) {
                $t[] = $value['id'];
            }
//            dd($t);
            $list = $obj->whereIn('user_id',$t)->whereNull('batch')->where('status',0)->orderBy('create_time','desc')->Paginate(10)->toArray();
            if($list == false && !empty($search)) {
                return  redirect()->back()->withInput()->withErrors('未查询到结果！');
            }
            $searchtype = self::$field;
            $ord = $obj->whereIn('user_id',$t)->where('status',0)->whereNull('batch')->Paginate(10);
        }
        return view('admin.orders.index',['list'=>$list,'searchtype'=>$searchtype,'ord'=>$ord]);
    }

    //载入已审核自助订单列表
    public function index2() {
        $search = input::get('searchtype');
        $param = input::get('param');
        $obj = new Orders;
        if($search == 1 ) {
            $obj = $obj->where('id','like',"%$param%");
        }elseif ($search == 2 ) {
            $obj = $obj->where('create_time','like',"%$param%");
        }elseif ($search == 3 ) {
            $obj = $obj->where('batch','like',"%$param%");
        }elseif ($search == 4 ) {
            $obj = $obj->where('order_id','like',"%$param%");
        }elseif ($search == 5 ) {
            $gname = Goods::where('goods_name','like',"%$param%")->first();
            if(!$gname) {
                return redirect()->back()->withInput()->withErrors('为搜索到该商品!');
            }
            $obj = $obj->where('goods_id','=',$gname->goods_name);
        }elseif ($search == 7 ) {
            $obj = $obj->where('total_price','like',"%$param%");
        }elseif ($search == 8 ) {
            $uname = Users::where('name','like',"%$param%")->first();
            if(!$uname) {
                return redirect()->back()->withInput()->withErrors('为搜索到该会员!');
            }
            $obj = $obj->where('user_id','=',$uname->name);
        }elseif ($search == 9 ) {
            $mname = Manage::where('username','like',"%$param%")->first();
            if(!$mname) {
                return redirect()->back()->withInput()->withErrors('为搜索到该客户经理!');
            }
            $obj = $obj->where('manage_id','=',$mname->username);
        }elseif ($search == 10 ) {
            if($param === "自取") {
                $p = 1;
            }
            if($param === "邮寄") {
                $p = 2;
            }
            $obj = $obj->where('get_way','=',$p);
        }elseif ($search == 11 ) {
            $obj = $obj->where('address','like',"%$param%");
        }elseif ($search == 12 ) {
            $obj = $obj->where('code','like',"%$param%");
        }elseif ($search == 13 ) {
            if($param === "已兑换") {
                $p = 1;
            }
            else {
                $p = 0;
            }
            $obj = $obj->where('status','=',$p);
        }
        $sid = Session::get('id');
        $roleid = Session::get('roleid');
        if($roleid == 1) {
            $list = $obj->whereNull('batch')->orderBy('create_time','desc')->where('audit',1)->Paginate(10)->toArray();
            if($list == false && !empty($search)) {
                return  redirect()->back()->withInput()->withErrors('未查询到结果！');
            }
            $searchtype = self::$field;
            $ord = $obj->whereNull('batch')->where('audit',1)->Paginate(10);
        }
        elseif ($roleid == 2 or $roleid ==3) {
            if($roleid == 3) {
                $pid = Manage::where('id',$sid)->first();
                $id = Manage::where('son_id',$pid['son_id'])->get()->toArray();
            }
            else {
                $id = Manage::where('son_id',$sid)->get()->toArray();
//                dump($id);
            }
            $d = array();
            $t = array();
            foreach ($id as $value) {
                $d[] = $value['id'];
            }
            $user = Users::whereIn('mid',$d)->get()->toArray();
            foreach ($user as $value) {
                $t[] = $value['id'];
            }
//            dump($t);
            $list = $obj->whereIn('user_id',$t)->whereNull('batch')->where('status',1)->orderBy('create_time','desc')->Paginate(10)->toArray();
//            dump($list);
            if($list == false && !empty($search)) {
                return  redirect()->back()->withInput()->withErrors('未查询到结果！');
            }
            $searchtype = self::$field;
            $ord = $obj->whereIn('user_id',$t)->where('status',1)->whereNull('batch')->Paginate(10);
        }
        else {
//            dump(Session::get('id'));
            $t = array();
            $user = Users::where('mid',Session::get('id'))->get()->toArray();
//            dump($);
            foreach ($user as $value) {
                $t[] = $value['id'];
            }
//            dd($t);
            $list = $obj->whereIn('user_id',$t)->whereNull('batch')->where('status',1)->orderBy('create_time','desc')->Paginate(10)->toArray();
            if($list == false && !empty($search)) {
                return  redirect()->back()->withInput()->withErrors('未查询到结果！');
            }
            $searchtype = self::$field;
            $ord = $obj->whereIn('user_id',$t)->where('status',1)->whereNull('batch')->Paginate(10);
        }
        return view('admin.orders.index',['list'=>$list,'searchtype'=>$searchtype,'ord'=>$ord]);
    }

    //
    public function orderList($id) {
        $list = Orders::where('id',$id)->first()->toArray();
        $goods = Goods::where('id',$list['goods_id'])->first()->toArray();
        $list['pic'] = $goods['goods_picture'];
        $list['intr'] = $goods['goods_introduce'];
        $list['name'] = $goods['goods_name'];
        $list['price'] = $goods['goods_price'];
        return view('admin.orders.orderList',['list'=>$list]);
    }

    //
    public function batch() {
//        $list = DB::table('orders')
//            ->whereNotNull('batch')
//            ->orderBy('create_time','desc')
//            ->get()
//            ->groupBy('batch');
        $last = file_get_contents("phone.txt");
        $lastPhone = explode(',',$last);

        return view('admin.orders.batch',['lastPhone'=>$lastPhone]);
    }

    //批量订单提交
    public function import() {
        $input_error = null;
        $phone = input::get('phone');
        $file = input::file('file');
        if(empty($file)) {
            return redirect()->back()->withInput()->withErrors('请选择上传文件!');
        }
        if($file->isValid()) {
           $allowed_extensions = ["xls", "xlsx"];
            if($file->getClientOriginalExtension() && !in_array($file->getClientOriginalExtension(),$allowed_extensions)) {
                return ['error' => 'You may only upload xls or xlsx.'];
            }
            $destinationPath = 'exports';  //public文件夹下新建storage/uploads文件夹
            $extension = $file->getClientOriginalExtension();
            $fileName = str_random(10) . '.' . $extension;
            $file->move($destinationPath,$fileName);
            $filePath = asset($destinationPath.'/'.$fileName);
        }
        DB::beginTransaction();
        try {
            $fileExcel = "exports/".iconv('UTF-8', 'UTF-8', $fileName);
            $result = Excel::load($fileExcel, function($reader) {
                $data = $reader->all();
//                dd($data);
                $o = date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
                foreach ($data as $da => $value) {
                    if(!empty($value['goods']) && !empty($value['number']) && !empty($value['name']) && !empty($value['manage_id'])) {
                        $uid = Users::where('car_num',$value['car_num'])->first();
                        $gid = Goods::where('goods_name',$value['goods'])->first();
                        $address = Address::where('user_id',$uid['id'])->first();
                        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
                        $order_id = $yCode[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
                        $list = Orders::insert([
                            'batch' => $o,
                            'order_id' => $order_id,
                            'goods_id' => $gid['id'],
                            'goods_num' => $value['number'],
                            'user_id' => $uid['id'],
                            'total_price' => $value['price']*$value['number'],
                            'manage_id' => $value['manage_id'],
//                            'address' => $uid['address'],
                            'get_way' => 0,
                        ]);
                    }

                }
            });
            DB::commit();
        }
        catch (\Exception $e) {
            return back()->withErrors('导入失败!');
            DB::rollBack();
        }
        //发送短信
        $n = Orders::whereNotNull('batch')->orderBy('create_time','desc')->first();
        $num = $n['batch'];
        $c = new TopClient();
        $p = [
            'number' => "$num",
        ];
        $pp = json_encode($p);
        //获取密钥
        $c->appkey = config('alisms.KEY');
        $c->secretKey = config('alisms.SECRETKEY');
        //设置参数
        $req = new AlibabaAliqinFcSmsNumSendRequest();
        $req->setSmsType('normal');
        $req->setSmsParam($pp);
        $req->setSmsFreeSignName('保祥云商城');
        $req->setRecNum($phone);
        $req->setSmsTemplateCode('SMS_36295157');
        $rsp = $c->execute($req);
        $rsp = json_encode($rsp, JSON_UNESCAPED_UNICODE);
        //发送邮件
//        $mail = Mail::raw('本次批次号为'.$num, function($message) use($filePath)
//        {
//            $message->from('18722343840@163.com', '文件审核');
//            $message->subject('批量导入文件审核');
//            $message->to('18722343840@163.com');
//            $message->attach($filePath);
//        });
        $flag = Mail::send('admin.orders.test',['name'=>$num],function($message) use($filePath)
        {
            $to = '18722343840@163.com';
            $message ->to($to)->subject('订单审核');
            $message->attach($filePath);
        });
//        Cookie::queue('lastPhone',$phone);
        $txt = 'phone.txt';
        file_put_contents($txt,",".$phone,FILE_APPEND | LOCK_EX);
//        File::put('','phone.txt');
        if(empty($flag)) {
            return Redirect::to('admin/batch')->withErrors('批量导入成功!');
        }
        else {
            return back()->withErrors('邮件发送失败!');
        }
    }

    //发送邮件
//    public function send()
//    {
//        $mail = Mail::raw('本次批次号为', function($message)
//        {
//            $message->from('18722343840@163.com', 'Laravel');
//            $message->subject('批量导入文件审核');
//            $message->to('18722343840@163.com');
//        });
//    }
        // 1
//        $name = '学院君';
//        $flag = Mail::send('admin.orders.test',['name'=>$name],function($message){
//            $to = '18325516110@163.com';
//            $message ->to($to)->subject('开发测试');
//            dump(123);
//        });
//        if($flag){
//            return Redirect::to('admin/batch')->withErrors('发送成功!');
//        }else{
//            return Redirect::to('admin/batch')->withErrors('发送失败!');
//        }

        // 2
//        $mail = Mail::raw('恭喜导入成功',function ($message) {
//            $message->subject('调试邮件');
//            $message->to('18325516110@163.com');
//        });
//
//        if($mail){
//            return Redirect::to('admin/batch')->withErrors('发送成功!');
//        }else{
//            return Redirect::to('admin/batch')->withErrors('发送失败!');
//        }

        // 3
//        $email = "18322516110@163.com";
//        $name = "test";
//        $uid = "11";
//        $code = "123123";
//        $data = ['email'=>$email, 'name'=>$name, 'uid'=>$uid, 'activationcode'=>$code];
//        $mail = Mail::send('admin.orders.test', $data, function($message) use($data)
//        {
//            $message->to($data['email'], $data['name'])->subject('欢迎注册我们的网站，请激活您的账号！');
//        });
//        dd($mail);
//        if($mail){
//            return Redirect::to('admin/batch')->withErrors('发送成功!');
//        }else{
//            return Redirect::to('admin/batch')->withErrors('发送失败!');
//        }

        // 4
//        $mail = Mail::raw('Text to e-mail', function($message)
//        {
//            $message->from('18722343840@163.com', 'Laravel');
//
//            $message->to('18325516110@163.com');
//            $message->attach($this->PathToFile);
//        });
//        dd($mail);
//    }

    //兑换订单
    public function setStatus()
    {
        $id = input::get('id');
        $select = input::get('select');
        $role = Session::get('roleid');
        if(!empty($role) && $role > 3){
//            return  redirect()->back()->withInput()->withErrors('没有权限！');
            return [
                'error'=>4,
                'msg'=>'没有权限!'
            ];
        }
        $c = Orders::where('id',$id)->first()->toArray();
        $user = Users::where('id',$c['user_id'])->first();
        $goods = Goods::where('id',$c['goods_id'])->first();
        if($user and $goods) {
            $total = (int)($goods['goods_price']) * (int)($c['goods_num']);
            $integral = (int)($user['integral']) - (int)($total);
            $num = (int)($goods['goods_inventory']) - (int)($c['goods_num']);
            if ((int)($integral) >= 0 and (int)($num) >= 0) {
                $u = Users::where('id', $c['user_id'])->update(['integral' => $integral]);
                $order = Orders::where('id', $id)->update(['total_price' => $total, 'status' => 1,'get_way'=>$select,'change_id'=>Session::get('id'),'time'=>date("Y-m-d H:i:s")]);
                if ($u and $order) {
                    $number = Goods::where('id', $c['goods_id'])->update(['goods_inventory' => $num]);
//                    return back()->withErrors('兑换成功');
                    return [
                        'error'=>1,
                        'msg'=>'兑换成功!'
                    ];
                } else {
//                    return back()-
                    return [
                        'error'=>2,
                        'msg'=>'兑换失败!'
                    ];
                }
            } else {
//                return redirect()->back()->withErrors('积分不足或库存不足!');
                return [
                    'error'=>3,
                    'msg'=>'积分不足或库存不足!'
                ];
            }
        }
        else {
//            return redirect()->back()->withErrors('客户或商品不存在!');
            return [
                'error'=>5,
                'msg'=>'客户或商品不存在!'
            ];
        }
    }

    //兑换订单
    public function oneStatus($id,$status)
    {
//        $id = input::get('id');
        $select = input::get('select');
        $role = Session::get('roleid');
        if(!empty($role) && $role > 3){
            return  redirect()->back()->withInput()->withErrors('没有权限！');
        }
        $c = Orders::where('id',$id)->first()->toArray();
        $user = Users::where('id',$c['user_id'])->first();
        $goods = Goods::where('id',$c['goods_id'])->first();
        if($user and $goods) {
            $total = (int)($goods['goods_price']) * (int)($c['goods_num']);
            $integral = (int)($user['integral']) - (int)($total);
            $num = (int)($goods['goods_inventory']) - (int)($c['goods_num']);
            if ((int)($integral) >= 0 and (int)($num) >= 0) {
                $u = Users::where('id', $c['user_id'])->update(['integral' => $integral]);
                $order = Orders::where('id', $id)->update(['total_price' => $total, 'status' => $status,'get_way'=>$select,'change_id'=>Session::get('id'),'time'=>date("Y-m-d H:i:s")]);
                if ($u and $order) {
                    $number = Goods::where('id', $c['goods_id'])->update(['goods_inventory' => $num]);
                    return redirect()->back()->withErrors('兑换成功');
                } else {
                    return redirect()->back()->withErrors('兑换失败');
                }
            } else {
                return redirect()->back()->withErrors('积分不足或库存不足!');
            }
        }
        else {
            return redirect()->back()->withErrors('客户或商品不存在!');
        }
    }

    //批量订单
//    public function audit() {
//        $v = array();
//        if(Session::get('roleid') !=1 ){
//            $list = Orders::where('manage_id',Session::get('id'))->whereNotNull('batch')->orderBy('create_time','desc')->get()->toArray();
//    //        if(empty($list)) {
//    //            return back()-
//    //        }
//            $first = Orders::where('manage_id',Session::get('id'))->whereNotNull('batch')->orderBy('create_time','desc')->first();
//            $map = Orders::where('batch',$first['batch'])->get()->toArray();
//        }
//        else {
//            $list = Orders::whereNotNull('batch')->orderBy('create_time','desc')->get()->toArray();
//            $first = Orders::whereNotNull('batch')->orderBy('create_time','desc')->first();
//            $map = Orders::where('batch',$first['batch'])->get()->toArray();
//        }
//        //dd($map);
//        foreach ($list as $l=>$value) {
//            $isin = in_array($value['batch'],$v);
//            if(!$isin) {
//                $v[] = $value['batch'];
//            }
//        }
//        $batch = input::get('batch');
//        if($batch) {
//            $l = Orders::where('batch',$batch)->get();
//            return view('admin.orders.audit',['list'=>$v,'order'=>$l]);
//        }
//        else {
//            return view('admin.orders.audit',['list'=>$v,'map'=>$map]);
//        }
//    }

    //载入未审核批次订单列表
    public function audit() {
        $v = array();
        $t = array();
        $y = array();
        $roleid = Session::get('roleid');
        if($roleid == 1) {
            $batch = Orders::whereNotNull('batch')->orderBy('create_time','desc')->orderBy('time','desc')->get();
            foreach ($batch as $l=>$value) {
                $isin = in_array($value['batch'],$v);
                if(!$isin) {
                    $map = Orders::where('batch',$value['batch'])->where('audit',0)->get()->toArray();
                    if(!empty($map)) {
                        $v[] = $value['batch'];
                        $t[] = $value;
                    }
                }
            }
        }
        elseif($roleid == 2 or $roleid == 3) {
            if($roleid == 3) {
                $pid = Manage::where('id',Session::get('id'))->first();
                $sid = Manage::where('son_id',$pid['son_id'])->get();
            }
            else {
                $sid = Manage::where('son_id',Session::get('id'))->get();
            }
            foreach($sid as $s) {
                $y[] = $s['id'];
            }
            $batch = Orders::whereIn('manage_id',$y)->whereNotNull('batch')->orderBy('create_time','desc')->orderBy('time','desc')->get();
            foreach ($batch as $l=>$value) {
                $isin = in_array($value['batch'],$v);
                if(!$isin) {
                    $map = Orders::where('batch',$value['batch'])->where('status',0)->get()->toArray();
                    if(!empty($map)) {
                        $v[] = $value['batch'];
                        $t[] = $value;
                    }
                }
            }
        }
        elseif($roleid == 4){
            $batch = Orders::where('manage_id',Session::get('id'))->whereNotNull('batch')->orderBy('create_time','desc')->orderBy('time','desc')->get();
            foreach ($batch as $l=>$value) {
                $isin = in_array($value['batch'],$v);
                if(!$isin) {
                    $map = Orders::where('batch',$value['batch'])->where('audit',0)->get()->toArray();
                    if(!empty($map)) {
                        $v[] = $value['batch'];
                        $t[] = $value;
                    }
                }
            }
        }
//        foreach ($batch as $l=>$value) {
//            $isin = in_array($value['batch'],$v);
//            if(!$isin) {
//                $map = Orders::where('batch',$value['batch'])->where('audit',0)->get()->toArray();
//                if(!empty($map)) {
//                    $v[] = $value['batch'];
//                    $t[] = $value;
//                }
//            }
//        }
        return view('admin.orders.audit',['v'=>$t]);
    }

    //载入已审核批次订单列表
    public function audit2() {
        $v = array();
        $t = array();
        $y = array();
        $roleid = Session::get('roleid');
        if($roleid == 1) {
            $batch = Orders::whereNotNull('batch')->orderBy('create_time','desc')->orderBy('time','desc')->get();
            foreach ($batch as $l=>$value) {
                $isin = in_array($value['batch'],$v);
                if(!$isin) {
                    $map = Orders::where('batch',$value['batch'])->where('audit',0)->get()->toArray();

                    if(empty($map)) {
                        $v[] = $value['batch'];
                        $t[] = $value;
                    }
                }
            }
//            dump($map);
        }
        elseif($roleid == 2 or $roleid == 3) {
            if($roleid == 3) {
                $pid = Manage::where('id',Session::get('id'))->first();
                $sid = Manage::where('son_id',$pid['son_id'])->get();
            }
            else {
                $sid = Manage::where('son_id',Session::get('id'))->get();
            }
            foreach($sid as $s) {
                $y[] = $s['id'];
            }
            $batch = Orders::whereIn('manage_id',$y)->whereNotNull('batch')->orderBy('create_time','desc')->orderBy('time','desc')->get();
            foreach ($batch as $l=>$value) {
                $isin = in_array($value['batch'],$v);
                if(!$isin) {
                    $map = Orders::where('batch',$value['batch'])->where('status',0)->get()->toArray();
                    if(empty($map)) {
                        $v[] = $value['batch'];
                        $t[] = $value;
                    }
                }
//                dump($map);
            }
        }
        else{
            $batch = Orders::where('manage_id',Session::get('id'))->whereNotNull('batch')->orderBy('create_time','desc')->orderBy('time','desc')->get();
            foreach ($batch as $l=>$value) {
                $isin = in_array($value['batch'],$v);
                if(!$isin) {
                    $map = Orders::where('batch',$value['batch'])->where('audit',0)->get()->toArray();
                    if(empty($map)) {
                        $v[] = $value['batch'];
                        $t[] = $value;
                    }
                }
            }
        }
//        foreach ($batch as $l=>$value) {
//            $isin = in_array($value['batch'],$v);
//            if(!$isin) {
//                $map = Orders::where('batch',$value['batch'])->where('audit',0)->get()->toArray();
//                if(empty($map)) {
//                    $v[] = $value['batch'];
//                    $t[] = $value;
//                }
//            }
//        }
        return view('admin.orders.audit',['v'=>$t]);
    }

    //查看详细
    public function toAudit($batch) {
        $list = Orders::where('batch',$batch)->orderBy('create_time','desc')->get()->toArray();
        return view('admin.orders.toAudit',['order'=>$list,'batch'=>$batch]);
    }

    //批量兑换
    public function audits() {
        $role = Session::get('roleid');
        if(!empty($role) && $role > 3){
            return  redirect()->back()->withInput()->withErrors('没有权限！');
        }
        $id = input::get('id');
        if(empty($id)) {
            return redirect()->back()->withErrors('请选择订单!');
        }
        $list = Orders::whereIn('id',$id)->get()->toArray();
        $a = 0;
        $b = 0;
        foreach ($list as $c) {

            if($c['status'] == 0) {
                $user = Users::where('id', $c['user_id'])->first();
                $goods = Goods::where('id', $c['goods_id'])->first();
                if ($user) {
                    if($goods) {
                        $total = (int)($goods['goods_price']) * (int)($c['goods_num']);
                        $integral = (int)($user['integral']) - (int)($total);
                        $num = (int)($goods['goods_inventory']) - (int)($c['goods_num']);
                        if ((int)($integral) >= 0 ) {
                            if((int)($num) >= 0) {
                                $u = Users::where('id', $c['user_id'])->update(['integral' => $integral]);
                                $order = Orders::where('id', $c['id'])->update(['total_price' => $total, 'status' => 1,'get_way'=>2,'change_id'=>Session::get('id'),'time'=>date("Y-m-d H:i:s")]);
                                if ($u and $order) {
                                    $number = Goods::where('id', $c['goods_id'])->update(['goods_inventory' => $num]);
                                    $a++;
                                    $b++;
                                    $res[] = '第'.$a .'条记录兑换成功!';
                                }
                                else {
                                    $a++;
                                    $res[] = '第'.$a .'条记录兑换失败!';
                                }
                            }
                            else {
                                $a++;
                                $res[] = '第'.$a .'条记录商品库存不足!';
                            }
                        }
                        else {
                            $a++;
                            $res[] = '第'.$a .'条记录客户积分不足!';
                        }
                    }
                    else {
                        $a++;
                        $res[] = '第'.$a .'条记录商品不存在!';
                    }
                }
                else {
                    $a++;
                    $res[] = '第'.$a .'条记录客户不存在!';
                }
            }
            elseif($c['status'] == 1) {
                $a++;
                $res[] = '第'.$a .'条记录已兑换!';
            }
        }

        return view('admin.orders.errors',['res'=>$res]);
    }

    //生成手机提示短信
    public function hintPhone()
    {

       // echo input::get('phone');
        $n = Orders::whereNotNull('batch')->orderBy('create_time','desc')->first();
        $num = $n['batch'];
        $phone = input::get('phone');
        $c = new TopClient();

//        //创建随机数
//        $num = rand(100000, 999999); //组装参数
        //生成json串
        $p = [
            'number' => "$num",
        ];
        $pp = json_encode($p);
        //获取密钥
        $c->appkey = config('alisms.KEY');
        $c->secretKey = config('alisms.SECRETKEY');
        //设置参数
        $req = new AlibabaAliqinFcSmsNumSendRequest();
        $req->setSmsType('normal');
        $req->setSmsParam($pp);
        $req->setSmsFreeSignName('保祥云商城');
        $req->setRecNum($phone);
        $req->setSmsTemplateCode('SMS_36295157');
        $rsp = $c->execute($req);
//        $vali = Cdkey::where('phone',$phone)->first();
//        return [
//            'a'=>123
//        ];
//        if ($vali) {
//            Cdkey::where('phone', $phone)->update(['code' => $num]);
//        } else {
//            Cdkey::insert([
//                'code' => $num,
//                'phone' => $phone
//            ]);
//        }
        echo $rsp = json_encode($rsp, JSON_UNESCAPED_UNICODE);
    }

    //管理员审核
    public function setAudit($id,$audit)
    {
        $role = Session::get('roleid');
        if(!empty($role) && $role != 1){
            return  back()->withErrors('没有权限！');
        }
        $c = Orders::where('id',$id)->where('audit',$audit)->get()->toArray();
        if($c){
            return  back()->withErrors('已经设置！');
        }
        $map = Orders::where('id',$id)->update(['audit'=>$audit]);
        if($map){
            return Redirect()->back()->withErrors('设置成功！');
        }else{
            return  back()->withErrors('设置失败！');
        }
    }

    //批量审核
    public function passAudit($batch) {
        if(Session::get('roleid') ==1) {
            $map = Orders::where('batch',$batch)->update(['audit'=>1]);
            if($map) {
                return back()->withErrors('审核成功!');
            }
            else{
                return back()->withErrors('审核失败!');
            }
        }
        else{
            return back()->withErrors('没有权限!');
        }
    }

    //添加订单
    public function addBatch() {
        $user_name = Input::get('user_name');
        $car_num = Input::get('car_num');
        $goods_name = Input::get('goods_name');
        $goods_num = Input::get('goods_num');
        $goods_price = Input::get('goods_price');
        $batch = Input::get('batch');
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
        $order_id = $yCode[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
        $goods = Goods::where('goods_name',$goods_name)->first();
        $user = Users::where('name',$user_name)->where('car_num',$car_num)->first();
        if(Session::get('roleid') != 3) {
            $list = Orders::insert([
                'order_id' => $order_id,
                'goods_id' => $goods['id'],
                'goods_num' => $goods_num,
                'total_price' => $goods_num *$goods_price,
                'user_id' => $user['id'],
                'manage_id' => Session::get('id'),
                'batch' => $batch,
            ]);
            if($list) {
                return [
                    'error' => 0,
                    'msg' => '添加成功!',
                ];
            }
            else {
                return [
                    'error' => 1,
                    'msg' => '添加失败!'
                ];
            }
        }
        else {
            return [
                'error' => 2,
                'msg' => '没有权限!'
            ];
        }
    }

    //更改收货方式
    public function chaAddre() {
        $get_way = Input::get('get_way');
        $oid = Input::get('id');
        $map = Orders::where('id',$oid)->update(['get_way'=>$get_way]);
        if($map){
            return [
                'error'=>0,
                'msg'=>'修改成功!'
            ];
        }
        else {
            return [
                'error'=>1,
                'msg'=>'修改失败!'
            ];
        }
    }

    //删除批次订单
    public function delete($batch) {
        $del = Orders::where('batch',$batch)->delete();
        if($del) {
            return back()->withErrors('删除成功!');
        }
        else {
            return back()->withErrors('删除失败!');
        }
    }

    //单条查询
    public function select() {
//        return 1;
        $phone = Input::get('param');
        if(empty($phone)) {
            return back()->withErrors('请输入手机号码!');
        }
        //dd($phone);
        $uid = Users::where('phone',$phone)->get();
//        dd($uid);
        foreach ($uid as $value) {
            $d[] = $value['id'];
        }
        if(empty($d)) {
            return back()->withErrors('号码不存在!');
        }
        $ord = Orders::whereIn('user_id',$d)->orderBy('create_time','desc')->get();
        return view('admin/orders/select',['ord'=>$ord]);
    }

    //查询兑换
    public function status()
    {
        $id = input::get('id');
        $role = Session::get('roleid');
        if(!empty($role) && $role > 3){
//            return  redirect()->back()->withInput()->withErrors('没有权限！');
            return [
                'error' => 3,
                'msg' => '没有权限!'
            ];
        }
        $c = Orders::where('id',$id)->first()->toArray();
        $user = Users::where('id',$c['user_id'])->first();
        $goods = Goods::where('id',$c['goods_id'])->first();
        if($user and $goods) {
            $total = (int)($goods['goods_price']) * (int)($c['goods_num']);
            $integral = (int)($user['integral']) - (int)($total);
            $num = (int)($goods['goods_inventory']) - (int)($c['goods_num']);
            if ((int)($integral) >= 0 and (int)($num) >= 0) {
                $u = Users::where('id', $c['user_id'])->update(['integral' => $integral]);
                $order = Orders::where('id', $id)->update(['total_price' => $total, 'status' => 1,'change_id'=>Session::get('id'),'time'=>date("Y-m-d H:i:s")]);
                if ($u && $order) {
                    $number = Goods::where('id', $c['goods_id'])->update(['goods_inventory' => $num]);
//                    return Redirect::to('admin/audit1')->withErrors('兑换成功!');
                    return [
                        'error' => 1,
                        'msg' => '兑换成功!'
                    ];
                } else {
//                    return back()->withErrors('兑换失败');
                    return [
                        'error' => 2,
                        'msg' => '兑换失败!'
                    ];
                }
            } else {
//                return back()->withErrors('积分不足或库存不足!');
                return [
                    'error' => 4,
                    'msg' => '积分不足或库存不足!'
                ];
            }
        }
        else {
//            return back()->withErrors('客户或商品不存在!');
            return [
                'error' => 5,
                'msg' => '客户或商品不存在!'
            ];
        }
    }

    #兑换服务载入
    public function server()
    {
        return view('admin.orders.server');
    }

    //导出订单信息
    public function pull($batch) {
        $list = Orders::where('batch',$batch)->get()->toArray();
//        dump($list);
//        $pull = null;
        $pull = [
            ['订单编号','订单批次号','会员名称','商品名称','商品数量','联系电话','地址','兑换人','兑换状态','领取方式']
        ];

        foreach ($list as $value) {
            if($value['status'] ==1) {
                $status = '已兑换';
            }
            else {
                $status = '未兑换';
            }
            if($value['status'] ==2) {
                $way = '邮寄';
            }
            elseif($value['status'] ==1) {
                $way = '自取';
            }
            else{
                $way = '未选择';
            }
            $user = Users::where('id',$value['user_id'])->first();
            $goods = Goods::where('id',$value['goods_id'])->first();
            $manage = Manage::where('id',$value['change_id'])->first();
            $address = Address::where('id',$value['address'])->first();
            $t[0] = $value['id'];
            $t[1] = $value['batch'];
            $t[2] = $user['name'];
            $t[3] = $goods['goods_name'];
            $t[4] = $value['goods_num'];
            $t[5] = $user['phone'];
            $t[6] = $user['address'];
            $t[7] = $manage['username'];
            $t[8] = $status;
            $t[9] = $way;
            $pull[] = $t;
        }
        Excel::create('orders',function($excel) use ($pull) {
            $excel->sheet('score',function ($sheet) use ($pull) {
                $sheet->rows($pull);
            });
        })->export('xls');
    }
}

